<script setup lang="ts">
import {onMounted} from "vue";
import * as echarts from "echarts";
import {invoke} from "@tauri-apps/api/core";

let myChart: echarts.ECharts | null = null;
const xAxisData: string[] = [];
const seriesData: number[] = [];

onMounted(() => {
  // 基于准备好的 dom，初始化 echarts 实例
  myChart = echarts.init(document.getElementById('main'));
  // 绘制初始图表
  myChart.setOption({
    title: {
      text: '系统内存使用'
    },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    yAxis: {
      type: 'value',
      max: 100.00
    },
    series: [
      {
        name: '销量',
        type: 'line',
        data: seriesData,
        smooth: true,
        symbol: 'none'
      }
    ]
  });

  // 每隔一秒更新一次数据
  setInterval(updateChart, 1000);

  //监听变化
  window.addEventListener("resize", resizeChart);
})

const updateChart = async () => {
  // 获取当前时间
  const now = new Date();
  const timeString = now.toLocaleTimeString();

  // 添加新数据
  xAxisData.push(timeString);
  invoke('mem_usage').then((result: any) => {
    seriesData.push(result as number);
  })

  // 如果数据超过100条，移除最早的数据
  if (xAxisData.length > 100) {
    xAxisData.shift();
    seriesData.shift();
  }

  // 更新图表
  if (myChart) {
    myChart.setOption({
      xAxis: {
        data: xAxisData
      },
      series: [
        {
          data: seriesData
        }
      ]
    }, false, true); // notMerge: false, lazyUpdate: true
  }
};

const resizeChart = async () => {
  if (myChart) {
    myChart.resize();
  }
};
</script>

<template>
  <div id="main" class="box"></div>
</template>

<style scoped>

.box {
  width: 100%; /* 占据 contain 的全部宽度 */
  height: 300px;
  background-color: rgb(188, 227, 236);
}
</style>